package javacommon.util;

import java.sql.Timestamp;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>Title: 日期处理类</p>
 * <p>Description: 日期处理类</p>
 * @author zbxu
 * @version $Revision: 1.4 $ $Date: 2006/10/27 11:46:35 $
 */
public class DateTools
{

    // the following const is to define date format.
    public static final int FMT_DATE_YYYYMMDD = 1;
    public static final int FMT_DATE_YYYYMMDD_HHMMSS = 2;
    public static final int FMT_DATE_HHMMSS = 3;
    public static final int FMT_DATE_HHMM = 4;


    /**
     * 将特定格式的字符串转换成java.util.Date对象<p>
     * 
     * @param strDate a date string
     * @param nFmtDate specific date string format defined in this class.
     * @return Date
     * @throws Exception
     */
    public static Date parseDate(String strDate, int nFmtDate) throws Exception
    {
        SimpleDateFormat fmtDate = new SimpleDateFormat();
        switch (nFmtDate) {
            default:
            case DateTools.FMT_DATE_YYYYMMDD:
                fmtDate.applyLocalizedPattern("yyyy-MM-dd");
                break;
            case DateTools.FMT_DATE_YYYYMMDD_HHMMSS:
                fmtDate.applyLocalizedPattern("yyyy-MM-dd HH:mm:ss");
                break;
            case DateTools.FMT_DATE_HHMM:
                fmtDate.applyLocalizedPattern("HH:mm");
                break;
            case DateTools.FMT_DATE_HHMMSS:
                fmtDate.applyLocalizedPattern("HH:mm:ss");
                break;
        }
        return fmtDate.parse(strDate);
    }

    /**
     * <p> 将两个日期进行比较，获取其相差的年份</p>
     * 
     * @param compDate1  ：指定的日期1
     * @param compDate2 ：指定的日期2
     * @return 相差的年份
     */
    public static long getAppoinDate(java.util.Date compDate1,java.util.Date compDate2)
    {
        if( compDate1 == null || compDate2 == null){            
            return -1;
        }

        long nYear = (compDate1.getTime() - compDate2.getTime()) / (24 * 3600 * 1000) / 365;

        return nYear;
    }
    /**
     * <p> 将现在的时间进行比较，获取其时间差</p>
     * 
     * @param otime  ：指定的日期1
     * @return 时间差     */
    public static String getAppoinTime(Date otime) {
		/** *//** 计算时间差 **/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String systemTime = sdf .format(new Date()).toString();
        Date ctime = null;
		try {
			ctime = sdf.parse(systemTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        long between = (ctime.getTime()-otime.getTime()) / 1000;//除以1000是为了转换成秒
        long month = between /(24*3600*30);
        long day = between /(24*3600);
        long hour = between %(24*3600)/3600;
        long minute = between %3600/60;
        long second = between %60;
        
        if(month > 0){
        	return month + "月前";
        }else if(day > 0){
        	return day + "天前";
        }else if(hour > 0){
        	return hour + "小时前";
        }else if(minute > 0){
        	return minute + "分钟前";
        }else if(second > 0){
        	return "1分钟内";
        }
		return "现在";
	}
    
    /**
     * <p> 获取持续时间</p>
     * 
     * @param b_time  ：开始时间
     * @param e_time  ：结束时间
     * @return 时间差
     */
    public static String getDuration(Date b_time,Date e_time) {
		/*计算持续时间*/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date ctime = null;
        if(e_time == null){
        	String systemTime = sdf .format(new Date()).toString();
        	try {
    			ctime = sdf.parse(systemTime);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
        }else{
        	ctime = e_time;
        }
        long between = (ctime.getTime()-b_time.getTime()) / 1000;//除以1000是为了转换成秒

        long month = between /(24*3600*30);
        long day = between /(24*3600);
        long hour = between %(24*3600)/3600;
        long minute = between %3600/60;
        long second = between %60;
        
        
        String duration = "持续";
        if(month > 0){
        	duration += month + "月";
        }else if(day > 0){
        	duration += day + "天";
        }else if(hour > 0){
        	duration += hour + "小时";
        }else if(minute > 0){
        	duration += minute + "分钟";
        }else if(second > 0){
        	duration += second+"秒";
        }else{
        	duration += "0秒";
        }
		return duration;
	}
    
    /**
     * @param otime
     * @param type	M月,D天,H小时,m分钟,S秒,
     * @return
     */
    public static long getAppoinTime(Date otime,String type) {
    	/** *//** 计算时间差 **/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String systemTime = sdf .format(new Date()).toString();
        Date ctime = null;
		try {
			ctime = sdf.parse(systemTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        long between = (ctime.getTime()-otime.getTime()) / 1000;//除以1000是为了转换成秒

        long month = between /(24*3600*30);
        long day = between /(24*3600);
        long hour = between %(24*3600)/3600;
        long minute = between %3600/60;
        long second = between %60;
        
        if("M".equals(type)){
        	return month;
        }else if("D".equals(type)){
        	return day;
        }else if("H".equals(type)){
        	return hour;
        }else if("m".equals(type)){
        	return minute;
        }else if("S".equals(type)){
        	return second;
        }
		return 0;
    }
    /**
     * <p> 将现在的时间进行比较，获取其相差天数</p>
     * 
     * @param otime  ：指定的日期1
     * @return 相差天数
     */
    public static long getAppoinDay(Date otime) {
		/** *//** 计算时间差 **/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String systemTime = sdf .format(new Date()).toString();
        Date ctime = null;
		try {
			ctime = sdf.parse(systemTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
        long between = (ctime.getTime()-otime.getTime()) / 1000;//除以1000是为了转换成秒
        long day = between /(24*3600);
        
		return day;
	}

    /**
     * 
     * <p> 比较时间应该在form.tmBegin.value,form.tmEnd.value之前 </p>
     * 
     * @param tmBegin
     * @param tmEnd
     * @param tmAlert
     * @return boolean
     */
    public static boolean compareTime(Date tmBegin, Date tmEnd, Date tmAlert)
    {
        boolean bReturn = false; 
        long lBegin = tmBegin.getTime();
        long lEnd = tmEnd.getTime();
        long lAlert = tmAlert.getTime();

        if (((lBegin - lAlert) < 0) && ((lAlert - lEnd) < 0)) {
            bReturn =  true;
        }
        return bReturn;
    }
    
    /**
     * 
     * <p> 比较时间tmBegin和tmEnd大小 </p>
     * 
     * @param tmBegin
     * @param tmEnd
     * @return boolean
     */
    public static boolean compareTime(Date tmBegin, Date tmEnd)
    {
        boolean bReturn = false; 
        long lBegin = tmBegin.getTime();
        long lEnd = tmEnd.getTime();

        if (lBegin < lEnd) {
            bReturn =  true;
        }
        return bReturn;
    }

    /**
     * 日期格式的转换<p>
     *
     * @param ts Timestamp格式的时间
     * @return 日期字符串
     */
    public static String getDispalyDate(Timestamp ts)
    {
        if (ts == null) {
            return "";
        }
        return MessageFormat.format("{0,time,yyyy-MM-dd}", new Object[] {ts});
    }

    /**
     * 显示当前日期
     * 
     * @return 日期字符串
     */
    public static String getDisplayDate() {
        return MessageFormat.format("{0,time,yyyy-MM-dd}", new Object[] {DateTools.getCurrentTime()});
    }
    
    public static String getDisplayDate(Date time) {
        return MessageFormat.format("{0,time,yyyy-MM-dd}", new Object[] {time});
    }
    
    /**
     * 显示当前日期
     * 
     * @return 日期字符串

     */
    public static String getDisplayDate(String format) {
        return MessageFormat.format("{0,time,"+format+"}", new Object[] {DateTools.getCurrentTime()});
    }

    /**
     * 将日期字符串转成timestamp<p>
     * 
     * @param strDate 日期字符串
     * @return timestamp类型格式的时间
     */
    public static Timestamp getTimestampTime(String strDate)
    {
    	if (strDate.length() == 10) {
    		strDate = strDate + " 00:00:00";
    	}
    	if (strDate.length() == 16) {
    		strDate = strDate + ":00";
    	}
        return getTimestamp(strDate, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 将日期字符串转成timestamp<p>
     * 
     * @param strDate 日期字符串
     * @return timestamp类型格式的时间
     */
    public static Timestamp getTimestamp(String strDate)
    {
        return getTimestamp(strDate, "yyyy-MM-dd");
    }


    /**
     * 将日期字符串转成timestamp<p>
     * 
     * @param strDate 日期字符串
     * @return timestamp类型格式的时间
     */
    public static Timestamp getTimestamp(String strDate, String strFormat)
    {
        if (strDate == null || strDate.equals("")) {
            return null;
        }

        SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
        Date date = null;

        try {
            date = sdf.parse(strDate);
        } catch (ParseException pe) {
            throw new RuntimeException("错误的日期字符串！");
        }

        return new Timestamp(date.getTime());
    }
    
    /**
     * 显示时间<p>
     *
     * @param ts 时间
     * @return 时间字符串
     */
    public static String getDisplayTime(Timestamp ts) {
        if (ts == null) {
            return "";
        }
        return MessageFormat.format("{0,time,yyyy-MM-dd HH:mm:ss}", new Object[] {ts});
    }


    /**
     * 显示当前时间<p>
     * 
     * @return 时间字符串
     */
    public static String getDisplayTime() {
        return MessageFormat.format("{0,time,yyyy-MM-dd HH:mm:ss}", new Object[] {DateTools.getCurrentTime()});
    }


    /**
     * 获取当前时间<p>
     *
     * @return 当前时间
     */
    public static Timestamp getCurrentTime() {
        return new Timestamp(System.currentTimeMillis());
    }

    /**
     * 在字串前面增加字符到指定长度<p>
     *
     * @param str 字符串
     * @param c 字符
     * @param len 长度
     * @return 定长字符串
     */
    public static String getFixedString(String str, char c, int len) {

        String strResult = "";

        for (int i = 0; i < len - str.length(); i++) {
            strResult += c;
        }

        return strResult + str;
    }
    
    public static boolean compTime(int startHour,int startMinute,int endHour,int endMinute){
    	Calendar curr = Calendar.getInstance();
		Calendar start = Calendar.getInstance();
		Calendar end = Calendar.getInstance();
		
		int currHour = curr.get(curr.HOUR_OF_DAY);
		int currMinute = curr.get(curr.MINUTE);
		int currDay = curr.get(curr.DATE);
		
		curr.set(Calendar.HOUR_OF_DAY, currHour);
		curr.set(Calendar.MINUTE, currMinute);
		Date currDate = curr.getTime();
		
		start.set(Calendar.HOUR_OF_DAY, startHour);
		start.set(Calendar.MINUTE, startMinute);
		Date startDate = start.getTime();
		
		end.set(Calendar.HOUR_OF_DAY, endHour);
		end.set(Calendar.MINUTE, endMinute);
		Date endDate = end.getTime();
		
		if(currDate.after(startDate) && currDate.before(endDate)){
			return true;
		}else{
			return false;
		}
    }
    
    public static boolean compTimeBefore(int startHour,int startMinute){
    	Calendar curr = Calendar.getInstance();
		Calendar start = Calendar.getInstance();
		
		int currHour = curr.get(curr.HOUR_OF_DAY);
		int currMinute = curr.get(curr.MINUTE);
		int currDay = curr.get(curr.DATE);
		
		curr.set(Calendar.HOUR_OF_DAY, currHour);
		curr.set(Calendar.MINUTE, currMinute);
		Date currDate = curr.getTime();
		
		start.set(Calendar.HOUR_OF_DAY, startHour);
		start.set(Calendar.MINUTE, startMinute);
		Date startDate = start.getTime();
		
		if(currDate.before(startDate)){
			return true;
		}else{
			return false;
		}
    }
    
    public static boolean compAfter(int endHour,int endMinute){
    	Calendar curr = Calendar.getInstance();
		Calendar end = Calendar.getInstance();
		
		int currHour = curr.get(curr.HOUR_OF_DAY);
		int currMinute = curr.get(curr.MINUTE);
		int currDay = curr.get(curr.DATE);
		
		curr.set(Calendar.HOUR_OF_DAY, currHour);
		curr.set(Calendar.MINUTE, currMinute);
		Date currDate = curr.getTime();
		
		end.set(Calendar.HOUR_OF_DAY, endHour);
		end.set(Calendar.MINUTE, endMinute);
		Date endDate = end.getTime();
		
		if(currDate.after(endDate)){
			return true;
		}else{
			return false;
		}
    }
    
    
    public static boolean ifWeek(){
    	Calendar calendar = Calendar.getInstance(); 
    	calendar.setTime(DateTools.getCurrentTime()); 
    	int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    	if(dayOfWeek == 7 || dayOfWeek == 1){
    		return true;
    	}else{
    		return false;
    	}
    }
   
}
